/*
 * Copyright 2010 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;


public class PennQuiz extends Activity {

    // Your Facebook Application ID must be set before running this example
    // See http://www.facebook.com/developers/createapp.php
    public static final String APP_ID = "200186583340324";

    private LoginButton mLoginButton;
    private TextView mText;
    /*private Button mRequestButton;
    private Button mPostButton;
    private Button mDeleteButton;
    private Button mUploadButton;*/
    private Button mChange;
    private Button mScoreboard;
    private Button mSinglePlay;
    private Button mNotifications;

    private Facebook facebook;
    private AsyncFacebookRunner mAsyncRunner;
    
    private static String me;
    private static String myID;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (APP_ID == null) {
            Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " +
                    "specified before running this example: see Example.java");
        }

        setContentView(R.layout.main);
        mLoginButton = (LoginButton) findViewById(R.id.login);
        mText = (TextView) PennQuiz.this.findViewById(R.id.txt);
        /*mRequestButton = (Button) findViewById(R.id.requestButton);
        mPostButton = (Button) findViewById(R.id.postButton);
        mDeleteButton = (Button) findViewById(R.id.deletePostButton);
        mUploadButton = (Button) findViewById(R.id.uploadButton);*/
        
        // My Buttons
        mChange = (Button) findViewById(R.id.changeButton);
        mScoreboard = (Button) findViewById(R.id.scoreBoard);
        mSinglePlay = (Button) findViewById(R.id.singlePlay);
        mNotifications = (Button) findViewById(R.id.notifications);

       	facebook = new Facebook(APP_ID);
       	mAsyncRunner = new AsyncFacebookRunner(facebook);
       	
       	// This actualizes the session by retrieving the session key
       	// if present
        SessionStore.restore(facebook, this);
        // This is a listener that gets activated once you log in
        SessionEvents.addAuthListener(new SampleAuthListener());
        // This is a listener that gets activated once you log out
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        
        // Prepare Data
        getData(facebook);
        
        /* LoginButton.class init() method.
         * init() has two constructors: with and without permissions
         * @param specify permissions
         */
        mLoginButton.init(this, facebook, new String[] {"publish_stream", "offline_access"});

        /*mRequestButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	mAsyncRunner.request("me", new SampleRequestListener());
            }
        });
        mRequestButton.setVisibility(facebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);

        mUploadButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Bundle params = new Bundle();
                params.putString("method", "photos.upload");

                URL uploadFileUrl = null;
                try {
                    uploadFileUrl = new URL(
                        "http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
                } catch (MalformedURLException e) {
                	e.printStackTrace();
                }
                try {
                    HttpURLConnection conn= (HttpURLConnection)uploadFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    int length = conn.getContentLength();

                    byte[] imgData =new byte[length];
                    InputStream is = conn.getInputStream();
                    is.read(imgData);
                    params.putByteArray("picture", imgData);

                } catch  (IOException e) {
                    e.printStackTrace();
                }

                mAsyncRunner.request(null, params, "POST",
                        new SampleUploadListener(), null);
            }
        });
        
        mUploadButton.setVisibility(facebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);*/
        
        
        // The Notifications button
        mNotifications.setVisibility(facebook.isSessionValid() ?
        		View.VISIBLE :
        		View.INVISIBLE);
        
        mNotifications.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Begin the loading dialog
				final ProgressDialog progress = ProgressDialog.show(
						PennQuiz.this, "", "Retrieving notifications...", true);
			    
				// Try to retrieve the friends from Facebook
			    String myFriends = getFriendsJSONString(facebook);
	            
			    final Intent intent = new Intent(v.getContext(), Notifications.class);
	            // I am sending the APP_ID and the friends 
			    // on the other side to connect both
			    // and the userID
	            intent.putExtra("api", APP_ID);
	            intent.putExtra("friends", myFriends);
	            intent.putExtra("myID", myID);
	            // Put the dialog in a new thread so that it can close 
	            // properly afterwards
	            new Thread(new Runnable(){
	            	public void run(){
	            		startActivity(intent);
	            		progress.dismiss();
	            	}
	            	}).start();
	            //startActivity(intent);
			}
        	
        });
        
        
        // The Single Play button
        mSinglePlay.setVisibility(facebook.isSessionValid() ?
        		View.VISIBLE :
        		View.INVISIBLE);
        
        mSinglePlay.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// Begin the loading dialog
				final ProgressDialog progress = ProgressDialog.show(
						PennQuiz.this, "", "Loading...", true);
				
				String[] questions = getQuestions();
	            
			    final Intent intent = new Intent(v.getContext(), SinglePlay.class);
	            // I am sending the APP_ID and the friends 
			    // on the other side to connect both
			    // and the userID
	            intent.putExtra("api", APP_ID);
	            intent.putExtra("questions", questions);
	            intent.putExtra("myID", myID);
	            intent.putExtra("score", 0);
	            // Put the dialog in a new thread so that it can close 
	            // properly afterwards
	            new Thread(new Runnable(){
	            	public void run(){
	            		startActivity(intent);
	            		progress.dismiss();
	            	}
	            	}).start();
	            //startActivity(intent);
			}
        	
        });
        
        // The Challenge! button
        mChange.setVisibility(facebook.isSessionValid() ?
        		View.VISIBLE :
        		View.INVISIBLE);
        
        mChange.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Begin the loading dialog
				final ProgressDialog progress = ProgressDialog.show(
						PennQuiz.this, "", "Retrieving friends...", true);
			    
				// Try to retrieve the friends from Facebook
			    String myFriends = getFriendsJSONString(facebook);
	            
			    final Intent intent = new Intent(v.getContext(), Challenge.class);
	            // I am sending the APP_ID and the friends 
			    // on the other side to connect both
			    // and the userID
	            intent.putExtra("api", APP_ID);
	            intent.putExtra("friends", myFriends);
	            intent.putExtra("myID", myID);
	            // Put the dialog in a new thread so that it can close 
	            // properly afterwards
	            new Thread(new Runnable(){
	            	public void run(){
	            		startActivity(intent);
	            		progress.dismiss();
	            	}
	            	}).start();
	            //startActivity(intent);
			}
        });
        
        // The scoreboard button
        mScoreboard.setVisibility(facebook.isSessionValid() ?
        		View.VISIBLE :
            	View.INVISIBLE);
        
        mScoreboard.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Begin the loading dialog
				final ProgressDialog progress = ProgressDialog.show(
						PennQuiz.this, "", "Getting scores...", true);
				
				// Retrieve the JSON String of friends from Facebook
				String myFriends = getFriendsJSONString(facebook);
	            
			    final Intent intent = new Intent(v.getContext(), Scoreboard.class);
	            // I am sending the APP_ID and the friends 
			    // on the other side to connect both
			    // and the userID
	            intent.putExtra("api", APP_ID);
	            intent.putExtra("friends", myFriends);
	            intent.putExtra("myID", myID);
	            // Put the dialog in a new thread so that it can close 
	            // properly afterwards
	            new Thread(new Runnable(){
	            	public void run(){
	            		startActivity(intent);
	            		progress.dismiss();
	            	}
	            	}).start();
	            //startActivity(intent);
			}
        });
        
        /*mPostButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                facebook.dialog(Example.this, "feed",
                        new SampleDialogListener());
            }
        });
        mPostButton.setVisibility(facebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);*/
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      facebook.authorizeCallback(requestCode, resultCode, data);
      // ... anything else your app does onActivityResult ...
    }


    public class SampleAuthListener implements AuthListener {

        public void onAuthSucceed() {
            mText.setText("You have logged in! ");
            /*mRequestButton.setVisibility(View.VISIBLE);
            mUploadButton.setVisibility(View.VISIBLE);
            mPostButton.setVisibility(View.VISIBLE);*/
            mNotifications.setVisibility(View.VISIBLE);
            mSinglePlay.setVisibility(View.VISIBLE);
            mChange.setVisibility(View.VISIBLE);
            mScoreboard.setVisibility(View.VISIBLE);
            
            // Get Data
            getData(facebook);
            
            // Add user to database if not there!
		    String domain = "http://www.pennquiz.com/users.php";
		    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("uid",myID));
		    nameValuePairs.add(new BasicNameValuePair("funct","addNewUser"));
		    RequestPoster rp = new RequestPoster(domain, nameValuePairs);
		    rp.execute();
        }

        public void onAuthFail(String error) {
            mText.setText("Login Failed: " + error);
        }
    }

    public class SampleLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
            mText.setText("Logging out...");
        }

        public void onLogoutFinish() {
            mText.setText("You have logged out! ");
            /*mRequestButton.setVisibility(View.INVISIBLE);
            mUploadButton.setVisibility(View.INVISIBLE);
            mPostButton.setVisibility(View.INVISIBLE);*/
            mNotifications.setVisibility(View.INVISIBLE);
            mSinglePlay.setVisibility(View.INVISIBLE);
            mChange.setVisibility(View.INVISIBLE);
            mScoreboard.setVisibility(View.INVISIBLE);
        }
    }

    public class SampleRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: executed in background thread
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String name = json.getString("name");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                PennQuiz.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mText.setText("Hello there, " + name + "!");
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }

    public class SampleUploadListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: (executed in background thread)
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String src = json.getString("src");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                PennQuiz.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mText.setText("Hello there, photo has been uploaded at \n" + src);
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }
    public class WallPostRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            Log.d("Facebook-Example", "Got response: " + response);
            String message = "<empty>";
            try {
                JSONObject json = Util.parseJson(response);
                message = json.getString("message");
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
            final String text = "Your Wall Post: " + message;
            PennQuiz.this.runOnUiThread(new Runnable() {
                public void run() {
                    mText.setText(text);
                }
            });
        }
    }

    public class WallPostDeleteListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            if (response.equals("true")) {
                Log.d("Facebook-Example", "Successfully deleted wall post");
                PennQuiz.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //mDeleteButton.setVisibility(View.INVISIBLE);
                        mText.setText("Deleted Wall Post");
                    }
                });
            } else {
                Log.d("Facebook-Example", "Could not delete wall post");
            }
        }
    }

    public class SampleDialogListener extends BaseDialogListener {

        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");
            if (postId != null) {
                Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
                mAsyncRunner.request(postId, new WallPostRequestListener());
                /*mDeleteButton.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        mAsyncRunner.request(postId, new Bundle(), "DELETE",
                                new WallPostDeleteListener(), null);
                    }
                });
                mDeleteButton.setVisibility(View.VISIBLE);*/
            } else {
                Log.d("Facebook-Example", "No wall post made");
            }
        }
    }
    
    private static String getFriendsJSONString(Facebook facebook){
    	// Try to retrieve the friends from Facebook
		String myFriends = "You haven't allowed permissions";
	    try {
	    	 myFriends = facebook.request("me/friends");
	    } catch (MalformedURLException e) {
	    	 // TODO Auto-generated catch block
	    	 e.printStackTrace();
	    } catch (IOException e) {
	    	 // TODO Auto-generated catch block
	    	 e.printStackTrace();
	    }
	    return myFriends;
    }
    
    private static void getData(Facebook facebook){
    	// Get the data about the user
        try{
	        me = facebook.request("me");
	        // Convert the string to JSON
	        JSONObject json = new JSONObject(me);
	        // Obtain myID
	        myID = json.getString("id");
        } catch(Exception e){
        	e.printStackTrace();
        }
    }
    
    // acquire 10 random questions and return their numbers
    private static String[] getQuestions(){
 	   InputStream is = null;
	   String result = "";
	   
	   String domain = "http://www.pennquiz.com/users.php";
	   ArrayList<NameValuePair> library = new ArrayList<NameValuePair>();
	   library.add(new BasicNameValuePair("funct","getQs"));
	   
	    //http post
	    try{
	            HttpClient httpclient = new DefaultHttpClient();
	            HttpPost httppost = new HttpPost(domain);
	            httppost.setEntity(new UrlEncodedFormEntity(library));
	            // Execute the MySQL command
	            HttpResponse response = httpclient.execute(httppost);
	            // Get the object from the execution
	            HttpEntity entity = response.getEntity();
	            is = entity.getContent();
	
	    }catch(Exception e){
	            Log.e("log_tag", "Error in http connection "+e.toString());
	    }
	
	    //convert response to string
	    try{
	            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                    sb.append(line);
	            }
	            is.close();
	            result=sb.toString().substring(1, sb.length()-1);
	            return result.split(",");
	            
	    }catch(Exception e){
	            Log.e("log_tag", "Error converting result "+e.toString());
	    }
    	return null;
    }

}
